package cn.sjxy.service;

import cn.sjxy.baseLib.SjuException;
import cn.sjxy.mapper.Mp_BookInfo;
import cn.sjxy.mapper.Mp_BookType;
import cn.sjxy.model.Md_BookInfo;
import cn.sjxy.model.Md_BookType;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 图书类型业务逻辑层
 */
@Service
public class Sv_BookType {

    @Autowired
    private Mp_BookType mp_bookType;

    @Autowired
    private Mp_BookInfo mp_bookInfo;

    /**
     * 检查类型编号是否存在
     * @param typeCode
     * @param excludeId 排除的ID（用于修改时）
     * @return
     */
    public boolean isTypeCodeExist(String typeCode, Long excludeId) {
        QueryWrapper<Md_BookType> wrapper = new QueryWrapper<>();
        wrapper.eq("typeCode", typeCode);
        if (excludeId != null) {
            wrapper.ne("id", excludeId);
        }
        Long count = mp_bookType.selectCount(wrapper);
        return count > 0;
    }

    /**
     * 删除图书类型（检查是否有图书使用）
     * @param typeCode
     * @throws Exception
     */
    public void deleteBookType(String typeCode) throws Exception {
        // 检查是否有图书使用该类型
        QueryWrapper<Md_BookInfo> bookWrapper = new QueryWrapper<>();
        bookWrapper.eq("typeCode", typeCode);
        Long bookCount = mp_bookInfo.selectCount(bookWrapper);
        
        if (bookCount > 0) {
            SjuException.appEx("该类型下有图书，无法删除");
        }

        // 删除类型
        QueryWrapper<Md_BookType> typeWrapper = new QueryWrapper<>();
        typeWrapper.eq("typeCode", typeCode);
        mp_bookType.delete(typeWrapper);
    }
}

